package service

import (
	"project-info/src/constants"
	"project-info/src/lib"
	"project-info/src/model"
)

type UserService struct{}

// IsAdmin 判断用户是否是管理员或者有admin角色
func (u *UserService) IsAdmin(token *lib.Token) (bool, error) {
	return isAdmin(token)
}

// HasPermission 判断用户是否具有某个权限
func HasPermission(c *lib.GinContext, token *lib.Token, permissionCode string) (bool, error) {
	isAdmin, err := isAdmin(token)
	if err != nil {
		return false, err
	}

	if isAdmin {
		return true, nil
	}

	var count int64
	if err := model.DB().Model(&model.MenuRole{}).
		Joins("left join menus on menus.id = menu_roles.menu_id").
		Joins("left join role_users on role_users.role_id = menu_roles.role_id").
		Where("role_users.user_id = ? and menus.btn_power = ? and menus.type = ?", token.UserId, permissionCode, "btn").
		Count(&count).Error; err != nil {
		return false, err
	}
	if count > 0 {
		return true, nil
	}
	return false, nil
}

// GetRoleIdsByUserId 获取用户的角色ID列表
func GetRoleIdsByUserId(c *lib.GinContext, userId uint64) ([]uint64, error) {
	var roleIds []uint64
	err := model.DB().Model(&model.RoleUser{}).Where("user_id = ?", userId).Pluck("role_id", &roleIds).Error
	if err != nil {
		return nil, err
	}
	return roleIds, nil
}

// GetUserListByRoleId 获取角色下的所有用户
func GetUserListByRoleId(roleId uint64) ([]*model.User, error) {
	var userList []*model.User
	err := model.DB().Model(&model.User{}).Joins("left join role_users on role_users.user_id = users.id").Where("role_users.role_id = ?", roleId).Find(&userList).Error
	if err != nil {
		return nil, err
	}
	return userList, nil
}

// isAdmin 判断用户是否是管理员或者有admin角色
func isAdmin(token *lib.Token) (bool, error) {
	// 1. 查询用户是否为admin
	if token.UserName == constants.AdminName {
		return true, nil
	}
	// 2. 查询用户是否有admin角色
	var roleId uint64
	err := model.DB().Select("id").Model(&model.Role{}).Where("role_name = ?", constants.AdminRoleName).First(&roleId).Error
	if err != nil {
		model.GloLogger.Error(err)
		return false, err
	}

	var count int64
	err = model.DB().Model(&model.RoleUser{}).Where("user_id = ? and role_id = ?", token.UserId, roleId).Count(&count).Error
	if err != nil || count == 0 {
		model.GloLogger.Error(err)
		return false, err
	}

	return true, nil
}
